#include <FileUtil.h>

namespace AsyncLogger {

	namespace FileUtil {
		AppendFile::AppendFile(const std::string& basename) :writtenBytes_(0)
		{
			fd_ = ::fopen(basename.c_str(), "a");
			assert(fd_ != nullptr);
		}

		AppendFile::~AppendFile()
		{
			assert(fd_ != nullptr);
			::fclose(fd_);
		}

		void AppendFile::append(const char* logline, size_t len)
		{
			// note: c风格文件异常处理
			size_t written = 0;
			while (written != len) {
				size_t remain = len - written;
				size_t n = write(logline, remain);
				if (n != remain) {
					int err = ferror(fd_);
					if (err) {
						fprintf(stderr, "AppendFile::append() failed %s\n", strerror(err));
						break;
					}
				}
				written += n;
			}
			writtenBytes_ += written;
			/* cpp 文件IO异常处理
				1、手动检查错误状态
				#include <iostream>
				#include <fstream>
				#include <string>

				int main() {
					std::ifstream file("nonexistent_file.txt");
					if (!file.is_open()) {
						std::cerr << "Failed to open file." << std::endl;
						return 1;
					}

					std::string line;
					while (std::getline(file, line)) {
						std::cout << line << std::endl;
					}

					if (file.fail() && !file.eof()) {
						std::cerr << "Error reading file." << std::endl;
					}

					file.close();
					return 0;
				}

				2、异常处理机制
				#include <iostream>
				#include <fstream>
				#include <string>

				int main() {
					try {
						// 打开文件并设置异常掩码
						std::ifstream file("nonexistent_file.txt");
						file.exceptions(std::ifstream::failbit | std::ifstream::badbit);

						std::string line;
						while (std::getline(file, line)) {
							std::cout << line << std::endl;
						}
					} catch (const std::ifstream::failure& e) {
						std::cerr << "File error: " << e.what() << std::endl;
						std::cerr << "Error code: " << e.code() << std::endl;
					}

					return 0;
				}
			*/
		}

		void AppendFile::flush()
		{
			::fflush(fd_);
		}

		size_t AppendFile::write(const char* logline, size_t len)
		{
			return ::fwrite(logline, 1, len, fd_);
		}
	}
}